<template>
  <div class="common-page page-policy-articles" v-loading.fullscreen="loading">
    <div class="common-page__head">
      <!-- <comp-paths class="route" :paths="['/policy', $route.fullPath]"></comp-paths> -->
      <div class="title">{{ $options.title }}</div>
    </div>
    <comp-policys class="common-page__body" ref="list" :type="type" select link>
      <template #head="scope">
        <el-button type="plain" size="small" icon="el-icon-refresh" @click="search()">刷新列表</el-button>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addPolicy()">添加</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" @click="delPolicy(...scope.selects)">删除
        </el-button>
      </template>
      <template #body="scope">
        <el-button type="primary" size="mini" @click.stop="getPolicy(scope.data)">详情</el-button>
        <el-button type="danger" size="mini" @click.stop="delPolicy(scope.data)">删除</el-button>
      </template>
    </comp-policys>
    <comp-dialog title="添加政策" ref="article">
      <el-form size="small" label-width="98px" style="margin-right:20px" @submit.native.prevent v-if="article">
        <!--                <el-form-item label="信息封面：">-->
        <!--                    <img style="display: block; margin: 0 10px 10px 0; max-width: 120px; height: 60px" :src="article.banner" v-if="article.banner" />-->
        <!--                    <el-button type="plain" icon="el-icon-plus" @click="addPolicy('upload-banner')">{{ article.banner ? "更换图片" : "选择图片" }}</el-button>-->
        <!--                </el-form-item>-->
        <el-form-item label="政策标题：" required>
          <el-input ref="articleTitle" type="textarea" v-model="article.title" style="width: 640px" placeholder="请输入"
                    :maxlength="100" :rows="2" resize="none" :readonly="loading"
                    @change="addPolicy('validate')"></el-input>
        </el-form-item>
<!--        <el-form-item label="政策编号：" required>-->
<!--          <el-input  v-model="article.no" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addPolicy('validate')"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="政策来源：" required>
          <el-input  v-model="article.policySource" style="width: 640px" placeholder="请输入政策单位" :maxlength="100" :readonly="loading" @change="addPolicy('validate')"></el-input>
        </el-form-item>
        <el-form-item label="政策要点：">
          <el-input  v-model="article.policyPoints" style="width: 640px" placeholder="请输入政策要点" :maxlength="100" :readonly="loading" @change="addPolicy('validate')"></el-input>
        </el-form-item>
        <el-form-item label="发文时间：" required>
          <el-date-picker  v-model="article.publishTime"
                           type="datetime"
                           style="width: 640px"
                           placeholder="请输入发文时间"
                           :value-format="'timestamp'"
                           :readonly="loading" @change="addPolicy('validate')"></el-date-picker>
        </el-form-item>
        <!--                <el-form-item label="信息摘要：">-->
        <!--                    <el-input type="textarea" v-model="article.summary" style="width: 640px" placeholder="请输入" :maxlength="200" :rows="5" resize="none" :readonly="loading" @change="addPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <el-form-item label="政策正文：">
          <comp-html-editor ref="articleContentEditor" style="width: 640px; height: 300px" editing
                            :content="article.content"></comp-html-editor>
        </el-form-item>
        <!--                <el-form-item label="信息来源：">-->
        <!--                    <el-input v-model="article.referer" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息原文：">-->
        <!--                    <el-input v-model="article.source" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息作者：">-->
        <!--                    <el-input v-model="article.author" style="width: 640px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息分类：">-->
        <!--                    <el-select v-model="article.tag.id" style="width: 640px" placeholder="请选择" @change="addPolicy('validate')">-->
        <!--                        <el-option v-for="data in tags" :key="data.id" :label="data.name" :value="data.id"></el-option>-->
        <!--                    </el-select>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="申报日期：">-->
        <!--                    <el-date-picker type="date" v-model="article.startTime" style="width: 306px" format="yyyy年M月d日" value-format="timestamp" placeholder="起始日期" :clearable="false" :readonly="loading" @change="addPolicy('validate')"></el-date-picker>-->
        <!--                    <span style="margin: 0 0.5em">至</span>-->
        <!--                    <el-date-picker type="date" v-model="article.endTime" style="width: 306px" format="yyyy年M月d日" value-format="timestamp" placeholder="截止日期" :clearable="false" :readonly="loading" @change="addPolicy('validate')"></el-date-picker>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息权重：">-->
        <!--                    <el-input v-model="article.weight" style="width: 640px" placeholder="请输入" :readonly="loading" @change="addPolicy('validate')"></el-input>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="发布时间：" required>-->
        <!--                    <el-date-picker-->
        <!--                      v-model="article.publishTime"-->
        <!--                      type="datetime"-->
        <!--                      value-format="timestamp"-->
        <!--                      placeholder="选择日期时间">-->
        <!--                    </el-date-picker>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="信息状态：">-->
        <!--                    <el-select v-model="article.published" style="width: 640px" placeholder="请选择" @change="addPolicy('validate')">-->
        <!--                        <el-option v-for="data in env.articlePublisheds" :key="data.id" :label="data.name" :value="data.value"></el-option>-->
        <!--                    </el-select>-->
        <!--                </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-check" @click="addPolicy('submit')">添加</el-button>
          <el-button type="plain" icon="el-icon-close" @click="addPolicy('end')">放弃</el-button>
        </el-form-item>
      </el-form>
    </comp-dialog>
  </div>
</template>

<script>
import mixin from "../mixin";
import {string, int, toMagicImgURL, selectFile} from "../util";
import env from "@/env";

export default {
  name: "page-up-policys",
  title: "政策管理",
  nodes: ["/menu/policyUp"],
  childs: ["up-policy"],
  mixins: [mixin],
  data: () => ({
    loading: false,
    type: "policy",
    article: null,
    tags: [],
    baseApiUrl: env.xhrPrefix,
  }),
  methods: {
    search() {
      if (this.loading) return;
      this.$nextTick(() => this.$refs.list.init());
    },
    addPolicy(action, data) {
      if (this.loading) return;
      let form = this.article;
      if (!action || action === "start") {
        // this.article = this.plugins.user.formatArticle();
        this.article = {
          title: '',
          content: ''
        };
        this.addPolicy("validate");
        this.$refs.article.init();
        this.$nextTick(() => this.$refs.articleTitle.focus());
        this.$nextTick(() => this.$refs.articleContentEditor.init());
      } else if (action === "validate") {
        let error = "";
        form.title = string(form.title).trim();
        error = error || (form.title ? "" : "请输入政策标题！");
        error = error || (form.policySource ? "" : "请输入政策来源！");
        error = error || (form.publishTime ? "" : "请选择发文时间！");
        form.content = string(() => this.$refs.articleContentEditor.getContent()) || string(form.content);
        if (data) this.plugins.modal.toast(error, "error");
        return !error;
      } else if (action === "upload-banner") {
        if (!data) return selectFile("image/*").then((file) => {
          if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
          else this.addPolicy(action, file);
        });
        let timer = null;
        let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
        this.loading = true;
        this.plugins.user.uploadFile(data, "image", progress).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            form.banner = this.baseApiUrl + "/user/sysStorage/getFile/" + res.data.id + "?id=" + res.data.id//toMagicImgURL(res.data.value, 120, 120);
            this.addPolicy("validate");
          } else {
            this.plugins.modal.alert("图片上传失败", res.code + "：" + res.msg, "error");
          }
        });
      } else if (action === "submit") {
        if (!this.addPolicy("validate", true)) return;
        this.loading = true;
        this.plugins.user.policyAdd(form).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.plugins.modal.toast("添加成功！", "success");
            this.addPolicy("end");
            this.search();
          } else {
            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
          }
        });
      } else if (action === "end") {
        this.$refs.article.close();
      }
    },
    getPolicy(article) {
      if (this.loading) return;
      this.$router.push("/up/policy?policyId=" + article.policyId);
    },
    delPolicy(...policys) {
      if (this.loading) return;
      if (policys.length === 0) return this.plugins.modal.toast("请先勾选要删除的信息哦！", "warning");
      let content = " <span style='color:red;'>" + (policys.length > 1 ? "勾选的" + policys.length + "篇信息" : policys[0].policyTitle) + "</span> 吗？";
      this.plugins.modal.alert("删除确认", "确定删除" + content, "warning", ["确定删除", "再想想"]).then((ok) => {
        if (!ok) return;
        this.loading = true;
        this.plugins.user.policyDel(...policys).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.plugins.modal.toast("删除成功！", "success");
            this.search();
          } else {
            this.plugins.modal.alert("删除失败", res.code + "：" + res.msg, "error");
          }
        });
      });
    },
    destroy() {
      if (this.loading) return;
      return true;
    },
    init() {
      if (this.loading) return;
      this.loading = true;
      this.$root.$refs.navbar.init();
      this.plugins.user.call(async () => {
        let res = await this.plugins.user.init();
        if (res.code === 0) {
        }
        return res;
      }, async () => {
        if (this.access(this.$route.name)) return {code: 0};
        return this.env.xhrErrors.find((error) => error.code === 4);
      }).then((res) => {
        this.loading = false;
        this.$root.$refs.navbar.init();
        if (res.code === 0) {
          this.search();
        } else if (res.code === 2) {
          this.$root.$refs.navbar.login();
        } else {
          this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/home"));
        }
      });
    },
  },
};
</script>

<style lang="scss">
.page-policy-articles {
  overflow: hidden;
}
</style>
